package com.aote.expression.paramprocessor;

import java.util.List;
import java.util.Map;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.aote.expression.Param;
import com.browsesoft.ExtendElement;
import com.browsesoft.PropertiesService;
import com.browsesoft.htmlcomponent.HTMLBasicComponent;
import com.browsesoft.user.User;

/**
 * 根据值的内容，取不同值
 */
public class CaseValueProcessor implements ParamProcessor {
	public String process(Param param, Map attribures, User loginUser,
			HTMLBasicComponent component) {
		// 取得case名
		Map map = param.getParams();
		String scase = (String) map.get("case");
		// 在组件里找到该名称的case元素
		Element ecase = getCase(component, scase);
		// 找到自动内容
		String field = ecase.getAttribute("field");
		String value = (String) attribures.get(field);
		// 对于每一个map对
		NodeList nl = ecase.getElementsByTagName("map");
		for (int i = 0; i < nl.getLength(); i++) {
			Element emap = (Element) nl.item(i);
			// 如果满足条件
			String swhen = emap.getAttribute("when");
			if (swhen.equals(value)) {
				// 返回值
				String result = emap.getAttribute("value");
				return result;
			}
		}
		throw new RuntimeException("找不到给定key的值:" + value);
	}

	private Element getCase(HTMLBasicComponent component, String scase) {
		Element result = null;
		List list = ExtendElement.findElementsByTagName(component.getElement(),
				"case", "name", scase);
		if (list == null || list.isEmpty()) {
			Element element = PropertiesService.getPropertiesFile()
					.getDocument().getDocumentElement();
			result = (Element) ExtendElement.findElementsByTagName(element,
					"case", "name", scase).get(0);
		} else {
			result = (Element) list.get(0);
		}
		return result;
	}
}
